{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "fdca5cce",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Package                   Version\n",
      "------------------------- --------------\n",
      "absl-py                   2.3.0\n",
      "anyio                     4.9.0\n",
      "argon2-cffi               25.1.0\n",
      "argon2-cffi-bindings      21.2.0\n",
      "arrow                     1.3.0\n",
      "asttokens                 3.0.0\n",
      "astunparse                1.6.3\n",
      "async-lru                 2.0.5\n",
      "attrs                     25.3.0\n",
      "babel                     2.17.0\n",
      "beautifulsoup4            4.13.4\n",
      "bleach                    6.2.0\n",
      "certifi                   2025.4.26\n",
      "cffi                      1.17.1\n",
      "charset-normalizer        3.4.2\n",
      "click                     8.2.1\n",
      "colorama                  0.4.6\n",
      "comm                      0.2.2\n",
      "contourpy                 1.3.2\n",
      "cycler                    0.12.1\n",
      "debugpy                   1.8.14\n",
      "decorator                 5.2.1\n",
      "defusedxml                0.7.1\n",
      "et_xmlfile                2.0.0\n",
      "executing                 2.2.0\n",
      "fastjsonschema            2.21.1\n",
      "filelock                  3.18.0\n",
      "fire                      0.7.0\n",
      "flatbuffers               25.2.10\n",
      "fonttools                 4.58.1\n",
      "fqdn                      1.5.1\n",
      "fsspec                    2025.5.1\n",
      "gast                      0.6.0\n",
      "google-pasta              0.2.0\n",
      "graphviz                  0.21\n",
      "grpcio                    1.73.0\n",
      "h11                       0.16.0\n",
      "h5py                      3.14.0\n",
      "httpcore                  1.0.9\n",
      "httpx                     0.28.1\n",
      "idna                      3.10\n",
      "imageio                   2.37.0\n",
      "ipykernel                 6.29.5\n",
      "ipython                   9.2.0\n",
      "ipython_pygments_lexers   1.1.1\n",
      "ipywidgets                8.1.7\n",
      "isoduration               20.11.0\n",
      "jedi                      0.19.2\n",
      "jieba                     0.42.1\n",
      "Jinja2                    3.1.6\n",
      "joblib                    1.5.1\n",
      "json5                     0.12.0\n",
      "jsonpointer               3.0.0\n",
      "jsonschema                4.24.0\n",
      "jsonschema-specifications 2025.4.1\n",
      "jupyter                   1.1.1\n",
      "jupyter_client            8.6.3\n",
      "jupyter-console           6.6.3\n",
      "jupyter_core              5.8.1\n",
      "jupyter-events            0.12.0\n",
      "jupyter-lsp               2.2.5\n",
      "jupyter_server            2.16.0\n",
      "jupyter_server_terminals  0.5.3\n",
      "jupyterlab                4.4.3\n",
      "jupyterlab_pygments       0.3.0\n",
      "jupyterlab_server         2.27.3\n",
      "jupyterlab_widgets        3.0.15\n",
      "kaggle                    1.7.4.5\n",
      "kagglehub                 0.3.12\n",
      "keras                     3.10.0\n",
      "kiwisolver                1.4.8\n",
      "libclang                  18.1.1\n",
      "lxml                      5.4.0\n",
      "Markdown                  3.8.2\n",
      "markdown-it-py            3.0.0\n",
      "MarkupSafe                3.0.2\n",
      "matplotlib                3.10.3\n",
      "matplotlib-inline         0.1.7\n",
      "mdurl                     0.1.2\n",
      "mistune                   3.1.3\n",
      "ml_dtypes                 0.5.1\n",
      "mpmath                    1.3.0\n",
      "namex                     0.1.0\n",
      "narwhals                  1.41.1\n",
      "nbclient                  0.10.2\n",
      "nbconvert                 7.16.6\n",
      "nbformat                  5.10.4\n",
      "nest-asyncio              1.6.0\n",
      "networkx                  3.5\n",
      "nltk                      3.9.1\n",
      "notebook                  7.4.3\n",
      "notebook_shim             0.2.4\n",
      "numpy                     2.1.3\n",
      "opencv-python-headless    4.11.0.86\n",
      "openpyxl                  3.1.5\n",
      "opt_einsum                3.4.0\n",
      "optree                    0.16.0\n",
      "overrides                 7.7.0\n",
      "packaging                 25.0\n",
      "pandas                    2.3.0\n",
      "pandocfilters             1.5.1\n",
      "parso                     0.8.4\n",
      "pdf2docx                  0.5.8\n",
      "pillow                    11.2.1\n",
      "pip                       25.1.1\n",
      "platformdirs              4.3.8\n",
      "plotly                    6.1.2\n",
      "prometheus_client         0.22.1\n",
      "prompt_toolkit            3.0.51\n",
      "protobuf                  5.29.5\n",
      "psutil                    7.0.0\n",
      "pure_eval                 0.2.3\n",
      "pycparser                 2.22\n",
      "pygame                    2.6.1\n",
      "Pygments                  2.19.1\n",
      "PyMuPDF                   1.26.1\n",
      "pyparsing                 3.2.3\n",
      "python-dateutil           2.9.0.post0\n",
      "python-docx               1.1.2\n",
      "python-json-logger        3.3.0\n",
      "python-slugify            8.0.4\n",
      "pytz                      2025.2\n",
      "pywin32                   310\n",
      "pywinpty                  2.0.15\n",
      "PyYAML                    6.0.2\n",
      "pyzmq                     26.4.0\n",
      "rawpy                     0.25.0\n",
      "referencing               0.36.2\n",
      "regex                     2024.11.6\n",
      "requests                  2.32.3\n",
      "rfc3339-validator         0.1.4\n",
      "rfc3986-validator         0.1.1\n",
      "rich                      14.0.0\n",
      "rpds-py                   0.25.1\n",
      "scikit-learn              1.7.0\n",
      "scipy                     1.15.3\n",
      "seaborn                   0.13.2\n",
      "Send2Trash                1.8.3\n",
      "setuptools                80.9.0\n",
      "six                       1.17.0\n",
      "sniffio                   1.3.1\n",
      "soupsieve                 2.7\n",
      "stack-data                0.6.3\n",
      "sympy                     1.14.0\n",
      "tensorboard               2.19.0\n",
      "tensorboard-data-server   0.7.2\n",
      "tensorflow                2.19.0\n",
      "termcolor                 3.1.0\n",
      "terminado                 0.18.1\n",
      "text-unidecode            1.3\n",
      "threadpoolctl             3.6.0\n",
      "tinycss2                  1.4.0\n",
      "torch                     2.7.1\n",
      "torchaudio                2.7.1\n",
      "torchvision               0.22.1\n",
      "torchviz                  0.0.3\n",
      "tornado                   6.5.1\n",
      "tqdm                      4.67.1\n",
      "traitlets                 5.14.3\n",
      "types-python-dateutil     2.9.0.20250516\n",
      "typing_extensions         4.14.0\n",
      "tzdata                    2025.2\n",
      "uri-template              1.3.0\n",
      "urllib3                   2.4.0\n",
      "wcwidth                   0.2.13\n",
      "webcolors                 24.11.1\n",
      "webencodings              0.5.1\n",
      "websocket-client          1.8.0\n",
      "Werkzeug                  3.1.3\n",
      "wheel                     0.45.1\n",
      "widgetsnbextension        4.0.14\n",
      "wrapt                     1.17.2\n",
      "xlrd                      2.0.1\n"
     ]
    }
   ],
   "source": [
    "!pip list\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "fd0be003",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([[2., 2., 2.],\n",
      "        [2., 2., 2.],\n",
      "        [2., 2., 2.],\n",
      "        [2., 2., 2.],\n",
      "        [2., 2., 2.]])\n",
      "tensor([[2., 2., 2.],\n",
      "        [2., 2., 2.],\n",
      "        [2., 2., 2.],\n",
      "        [2., 2., 2.],\n",
      "        [2., 2., 2.]])\n"
     ]
    }
   ],
   "source": [
    "import torch\n",
    "if torch.cuda.is_available():\n",
    "    device = torch.device(\"cuda:0\")\n",
    "    print(\"GPU is available\")\n",
    "else:\n",
    "    device = torch.device(\"cpu\")\n",
    "x = torch.ones(5, 3)\n",
    "y = torch.ones_like(x, device = device)\n",
    "x = x.to(device)\n",
    "z = x + y\n",
    "print(z)\n",
    "print(z.to(\"cpu\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "e220a0c9",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU time:  0.012\n"
     ]
    }
   ],
   "source": [
    "import time\n",
    "import torch\n",
    "x = torch.randn(500, 500)\n",
    "start_time = time.time()\n",
    "result = torch.matmul(x, x)\n",
    "end_time = time.time()\n",
    "print(\"CPU time: %6.5s\" % (end_time - start_time))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "b309f237",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "x的梯度: tensor([4.])\n",
      "y的梯度: tensor([2.])\n",
      "\n",
      "更复杂例子中x的梯度:\n",
      "tensor([[ 2.,  4.,  6.],\n",
      "        [ 8., 10., 12.]])\n"
     ]
    }
   ],
   "source": [
    "import torch\n",
    "\n",
    "# 创建需要求导的张量\n",
    "x = torch.tensor([2.0], requires_grad=True)\n",
    "y = torch.tensor([3.0], requires_grad=True)\n",
    "\n",
    "# 定义计算图\n",
    "z = x * y\n",
    "w = z + x\n",
    "\n",
    "# 计算反向传播\n",
    "w.backward()\n",
    "\n",
    "# 打印梯度\n",
    "print(f'x的梯度: {x.grad}')  # dy/dx = y + 1 = 4.0\n",
    "print(f'y的梯度: {y.grad}')  # dy/dy = x = 2.0\n",
    "\n",
    "# 另一个复杂一点的例子\n",
    "x = torch.tensor([[1., 2., 3.], [4., 5., 6.]], requires_grad=True)\n",
    "y = torch.sum(x * x)\n",
    "y.backward()\n",
    "\n",
    "print(f'\\n更复杂例子中x的梯度:\\n{x.grad}')  # 梯度是2x\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
